package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.beancontext.BeanContext;
import java.util.List;

/**
 * @Author by 孙有泽
 * @Date 2025/3/23 13:03
 * @Description
 */
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> list=addressBookMapper.list(userId);
        return list;
    }

    @Override
    public void save(AddressBook addressBook) {
        AddressBook addressBook1 = new AddressBook();
        BeanUtils.copyProperties(addressBook,addressBook1);

        //根据用户id查询用户 TODO
        addressBook1.setUserId(BaseContext.getCurrentId());
        addressBook1.setIsDefault(0);
        addressBookMapper.save(addressBook1);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);

    }

    @Override
    @Transactional
    public void setDefault(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);
        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }
    @Override
    public AddressBook getDefault() {
        List<AddressBook> aDefault = addressBookMapper.getDefault(BaseContext.getCurrentId());
        if (aDefault.size() > 0 && aDefault != null) {
            return aDefault.get(0);
        }
        return null;
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }
}
